package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BookManageActivity;
import com.jjwxc.jwjskandriod.activity.FindActivity;
import com.jjwxc.jwjskandriod.adapter.BookshelfAdapter;
import com.jjwxc.jwjskandriod.config.Constants;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.model.VipDistanceResponse;
import com.jjwxc.jwjskandriod.my.data.UserInfoBg;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.PopViewUtil;
import com.jjwxc.jwjskandriod.widget.ReadingHistoryPop;
import com.jjwxc.jwjskandriod.widget.ScreenPop;
import com.umeng.analytics.MobclickAgent;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

public class BookshelfFragment extends Fragment implements View.OnClickListener {
    private View view;

    private ImageView img_find;
    private ImageView img_gengduo;
    private TextView tv_saixuan;
    private TextView tv_bianji;
    private TextView tv_readtime;
    private View view_book;

    private LinearLayout ll_bg_vip;
    private ConstraintLayout cl_mainbg;
    /**
     * 菜单标题
     */
    private final String[] TAB_TITLES = new String[]{"全部收藏", "最近阅读"};

    ViewPager viewPager;
    TabLayout tabLayout;
    /**
     * 页卡适配器
     */
    private BookshelfAdapter adapter;

    private boolean mSelect = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_bookshelf, container, false);
            viewPager = view.findViewById(R.id.view_book_pager);
            tabLayout = view.findViewById(R.id.tab_book_layout);
            img_find = view.findViewById(R.id.img_find);
            img_gengduo = view.findViewById(R.id.img_gengduo);
            tv_saixuan = view.findViewById(R.id.tv_saixuan);
            tv_bianji = view.findViewById(R.id.tv_bianji);
            ll_bg_vip = view.findViewById(R.id.ll_bg_vip);
            cl_mainbg = view.findViewById(R.id.cl_mainbg);
            tv_readtime = view.findViewById(R.id.tv_readtime);
            view_book = view.findViewById(R.id.view_book);

            setTabs(tabLayout, getLayoutInflater(), TAB_TITLES);
            initPager();
            img_find.setOnClickListener(this);
            img_gengduo.setOnClickListener(this);
            tv_saixuan.setOnClickListener(this);
            tv_bianji.setOnClickListener(this);
        }
        return view;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        super.onResume();
        // 動態更新背景
        LiveEventBus.get(Constants.Background, Integer.class).observe(this, integer -> {
            if (integer < UserInfoBg.INSTANCE.getBACKGROUND_RID().length) {
                ll_bg_vip.setBackgroundResource(UserInfoBg.INSTANCE.getBACKGROUND_RID()[integer]);
            } else {
                ll_bg_vip.setBackgroundResource(R.color.white);
            }
        });
        tv_readtime.setText("今日阅读时长：0分钟");
        MobclickAgent.onEvent(getContext(), UMConstant.Page_Bookshelf_AllCollection);
        todayReadingTime(tv_readtime);
    }

    private void initPager() {
        adapter = new BookshelfAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);
        LinearLayout linearLayout = (LinearLayout) tabLayout.getTabAt(0).getCustomView();
        TextView textView = (TextView) linearLayout.getChildAt(0);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        // 关联切换
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //是不是切换到了第二个
                mSelect = tab.getPosition() != 0;
                // 取消平滑切换
                viewPager.setCurrentItem(tab.getPosition(), true);
                int s = tabLayout.getTabCount();
                if (tab.getPosition() == 0) {
                    tv_bianji.setVisibility(View.VISIBLE);
                    view_book.setVisibility(View.VISIBLE);
                } else {
                    tv_bianji.setVisibility(View.GONE);
                    view_book.setVisibility(View.GONE);
                    MobclickAgent.onEvent(getContext(), UMConstant.PAGE_BOOKSHELF_RECENT_READ);
                }
                for (int i = 0; i < s; i++) {
                    if (tab.getPosition() == i) {
                        LinearLayout linearLayout = (LinearLayout) tabLayout.getTabAt(i).getCustomView();
                        TextView textView = (TextView) linearLayout.getChildAt(0);
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    } else {
                        LinearLayout linearLayout = (LinearLayout) tabLayout.getTabAt(i).getCustomView();
                        TextView textView = (TextView) linearLayout.getChildAt(0);
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                        textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    }
                }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     * @param tabTitlees
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, String[] tabTitlees) {
        for (int i = 0; i < tabTitlees.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.bookshelf_item_menu, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_bookshelf_tab);
            tvTitle.setText(tabTitlees[i]);
            tabLayout.addTab(tab);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.img_find) {
            Intent intent = new Intent(getActivity(), FindActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.img_gengduo) {
            PopViewUtil.initPopWindow(v, getContext(), new PopViewUtil.PopDismissListener() {
                @Override
                public void onOkClick(String group) {
                    CollectFragment fragment = ((CollectFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_book_pager, 0));
                    int type = Integer.parseInt(group);
                    fragment.setViewType(type);
                    PreUtils.setInt("ViewType", type);
                }
            });
        } else if (v.getId() == R.id.tv_saixuan) {
            if (mSelect) {
                RecentlyFragment fragment = ((RecentlyFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_book_pager, 1));
                new ReadingHistoryPop().radingHistoryPopWindow(v, getActivity(), fragment.getScreenResponse(), new ReadingHistoryPop.ReadingHistoryListener() {
                    @Override
                    public void onValueClick(String value) {
                        fragment.setScreenResponse(value);
                    }
                });
                MobclickAgent.onEvent(getContext(), UMConstant.BOOKSHELF_FILTER_CLICK);
            } else {
                CollectFragment fragment = ((CollectFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_book_pager, 0));
                new ScreenPop().screenPopWindow(v, getActivity(), fragment.getScreenResponse(), new ScreenPop.ScreenListener() {
                    @Override
                    public void onValueClick(String value) {

                        fragment.setScreenResponse(value);
                    }
                });
            }
        } else if (v.getId() == R.id.tv_bianji) {
            CollectFragment fragment = ((CollectFragment) getFragemtn(adapter.getFragmentManager(), R.id.view_book_pager, 0));
            Intent intent = new Intent(getActivity(), BookManageActivity.class);
            intent.putExtra("book_tab", fragment.getSelectTab());
            startActivity(intent);
            MobclickAgent.onEvent(getContext(), UMConstant.BOOKSHELF_EDIT_CLICK);
        }

    }

    public Fragment getFragemtn(FragmentManager fragmentManager, int viewId, long id) {
        return fragmentManager.findFragmentByTag("android:switcher:" + viewId + ":" + id);
    }

    public void todayReadingTime(TextView textView) {
        ((FFActivity) getActivity()).post(Url.todayReadingTime, null, VipDistanceResponse.class, new FFNetWorkCallBack<VipDistanceResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(VipDistanceResponse response) {
                if (response.getCode() == 200) {
                    if (response.getData() > 60) {
                        tv_readtime.setText("今日阅读时长：" + response.getData() / 60 + "小时" + response.getData() % 60 + "分钟");
                    } else {
                        tv_readtime.setText("今日阅读时长：" + response.getData() + "分钟");
                    }
                }

            }

            @Override
            public boolean onFail(VipDistanceResponse response) {
                return false;
            }
        });
    }
}
